//
//  PhotoBrowserCell.swift
//  波波微博
//
//  Created by wave on 15/8/9.
//  Copyright © 2015年 wave. All rights reserved.
//

import UIKit

class PhotoBrowserCell: UICollectionViewCell {
    
    var imageURL:NSURL?{
        didSet{
        
            indicator.startAnimating()
            
            resetScrollView()
            
            imageView.image = nil
            //在这里要注意,并不是所有SDWebImage都能下载到图像
            imageView.sd_setImageWithURL(imageURL) { (image, _, _, _) -> Void in
                
                self.indicator.stopAnimating()
                
                if image == nil{
                    
                    print("下载图像错误")
                    return
                }
            
                //给图像赋值,并且调用设置图像位置函数
                self.setupImagePosetion()
            }
        }
    }
    
    //MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //计算显示的图像的大小,以scrollView的宽度为基准
    private func displaySize(image:UIImage) -> CGSize{
        
        //这里计算的宽度和高度的方式比较高明,这样让高/宽是为了算出比例,同时缩小多少倍
        let scale = image.size.height / image.size.width
        let height = scale * scrollView.bounds.width
        
        return CGSize(width: scrollView.bounds.width, height: height)
    }
    
    //设置图像的位置
    private func setupImagePosetion(){
        
        let size = self.displaySize(imageView.image!)
        //图像高度比视图高度小
        //短图
        if size.height < scrollView.bounds.height{
        
            let y = (scrollView.bounds.height - size.height) * 0.5
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            //设置间距,能够保证缩放完成后,同样能够显示完整画面
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: y, right: 0)
        }else{
            //长图
            imageView.frame = CGRect(origin: CGPointZero, size: size)
            scrollView.contentSize = size
        }
    }
    
    //准备ScrollView
    private func prepareScrollView(){
        
        scrollView.delegate = self
        
        //最大/最小缩放比例
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
    }
    
    private func resetScrollView(){
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
    }
    
    //MARK: - 界面搭建
    private func setupUI(){
    
        //添加控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        contentView.addSubview(indicator)
        
        //自动布局
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[sv]-20-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv":scrollView]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[sv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sv":scrollView]))
        //设置菊花的布局
        indicator.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: indicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
        
        prepareScrollView()
    }
    
    //MARK: - 懒加载
    lazy var scrollView = UIScrollView()
    lazy var imageView = UIImageView()
    //懒加载一个大菊花
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
}

extension PhotoBrowserCell: UIScrollViewDelegate{
    
    //告诉scrollView要缩放的控件
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        
        return imageView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        //通过transform改变view的缩放,bound本身没有变化,frame会变化
        
        UIView.animateWithDuration(0.5) { () -> Void in
            
//            var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
//            //如果边距小于0,需要修正
//            offsetX = offsetX < 0 ? 0 : offsetX
//            
//            var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
//            offsetY = offsetY < 0 ? 0 : offsetY
//            
//            scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
            
            //计算间距
                    let offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
                    let offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
                    scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        }
        
    }
    
}

